package main

import (
	"encoding/json"
	"errors"
	"time"

	"github.com/google/uuid"
)

type Item struct {
	Code      string    `db:"code" json:"code,omitempty"`
	UUID      string    `db:"uuid" json:"uuid"`
	Qty       int       `db:"qty" json:"qty,omitempty"`
	Spec      string    `db:"spec" json:"spec,omitempty"`
	Model     string    `db:"model" json:"model"`
	Brand     string    `db:"brand" json:"brand,omitempty"`
	Location  string    `db:"location" json:"location,omitempty"`
	CreatedAt time.Time `db:"created_at" json:"created_at,omitempty"`
	UpdatedAt time.Time `db:"updated_at" json:"updated_at,omitempty"`
}

// MarshalJSON 自定义JSON序列化，格式化时间字段
func (i Item) MarshalJSON() ([]byte, error) {
	type Alias Item
	return json.Marshal(&struct {
		*Alias
		CreatedAt string `json:"created_at,omitempty"`
		UpdatedAt string `json:"updated_at,omitempty"`
	}{
		Alias:     (*Alias)(&i),
		CreatedAt: i.CreatedAt.Format("2006-01-02 15:04:05"),
		UpdatedAt: i.UpdatedAt.Format("2006-01-02 15:04:05"),
	})
}

// UnmarshalJSON 自定义JSON反序列化，忽略时间戳字段
func (i *Item) UnmarshalJSON(data []byte) error {
	// 使用临时结构体来解析JSON，排除时间戳字段
	type Alias Item
	aux := &struct {
		*Alias
		CreatedAt interface{} `json:"created_at,omitempty"`
		UpdatedAt interface{} `json:"updated_at,omitempty"`
	}{
		Alias: (*Alias)(i),
	}

	if err := json.Unmarshal(data, &aux); err != nil {
		return err
	}

	// 时间戳字段会被忽略，保持零值
	return nil
}

// 添加物料
func ItemAdd(db *Db, item Item) error {
	// 生成UUID
	if item.UUID == "" {
		item.UUID = uuid.New().String()
	}

	tx := db.Sql.MustBegin()
	tx.NamedExec("INSERT INTO item (code, uuid, qty, spec, model, brand, location, created_at, updated_at) VALUES (:code, :uuid, :qty, :spec, :model, :brand, :location, :created_at, :updated_at)", item)
	return tx.Commit()
}

// 清空物料
func ItemCLear(db *Db) error {
	tx := db.Sql.MustBegin()
	tx.MustExec("DELETE FROM item")
	return tx.Commit()
}

// 更新物料
func ItemUpdate(db *Db, item Item) error {
	tx := db.Sql.MustBegin()
	if item.Code != "" {

		tx.NamedExec("UPDATE item SET qty = :qty, spec = :spec, model = :model, brand = :brand, location = :location, updated_at = :updated_at WHERE code = :code", item)
	} else {
		if item.Model != "" {
			tx.NamedExec("UPDATE item SET qty = :qty, spec = :spec, model = :model, brand = :brand, location = :location, updated_at = :updated_at WHERE model = :model", item)
		} else {
			return errors.New("model不能为空")
		}
	}
	return tx.Commit()
}

// 删除物料（通过code）
func ItemDel(db *Db, code string) error {
	tx := db.Sql.MustBegin()
	tx.MustExec("DELETE FROM item where code = ?", code)
	return tx.Commit()
}

// 删除物料（通过model）
func ItemDelByModel(db *Db, model string) error {
	tx := db.Sql.MustBegin()
	tx.MustExec("DELETE FROM item where model = ?", model)
	return tx.Commit()
}

// 获取所有物料
func ItemGetAll(db *Db) ([]Item, error) {
	items := []Item{}
	err := db.Sql.Select(&items, "SELECT * FROM item ORDER BY model ASC")
	return items, err
}

// 获取物料条目数量（通过code）
func ItemCount(db *Db, code string) int {
	var cnt int
	query := "SELECT COUNT(*) FROM item where code = ?"
	err := db.Sql.Get(&cnt, query, code)
	ck(err)
	return cnt
}

// 获取物料条目数量（通过model）
func ItemCountByModel(db *Db, model string) int {
	var cnt int
	query := "SELECT COUNT(*) FROM item where model = ?"
	err := db.Sql.Get(&cnt, query, model)
	ck(err)
	return cnt
}
